<template>
  <div class="student-statistics-container">
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <h2>学生维度统计</h2>
        </div>
      </template>

      <el-form :model="filterForm" label-width="100px" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="选择课程">
              <el-select
                v-model="filterForm.courseId"
                placeholder="请选择课程"
                style="width: 100%"
                @change="handleCourseChange"
              >
                <el-option
                  v-for="course in courses"
                  :key="course.id"
                  :label="course.name"
                  :value="course.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择班级">
              <el-select
                v-model="filterForm.classId"
                placeholder="请选择班级"
                style="width: 100%"
                :disabled="!filterForm.courseId"
              >
                <el-option
                  v-for="classItem in filteredClasses"
                  :key="classItem.id"
                  :label="classItem.name"
                  :value="classItem.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报告目录">
              <el-input
                v-model="filterForm.reportDirectory"
                placeholder="请输入实验报告目录路径"
              >
                <template #append>
                  <el-button @click="showDirectorySelector = true">
                    选择目录
                  </el-button>
                </template>
              </el-input>

              <!-- 文件系统目录选择器组件 -->
              <file-system-directory-selector
                v-model="showDirectorySelector"
                :initial-path="filterForm.reportDirectory"
                @select="handleDirectorySelected"
                @cancel="showDirectorySelector = false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="analyzeReports" :loading="analyzing">
            分析实验报告
          </el-button>
          <el-button type="success" @click="exportResults" :disabled="!hasResults">
            导出结果
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 异常信息提示 -->
    <el-card class="warning-card" v-if="hasResults && (invalidFileCount > 0 || unknownStudentCount > 0)">
      <el-alert
        type="warning"
        :closable="false"
        show-icon
      >
        <template #title>
          <div>扫描过程中发现以下问题：</div>
        </template>
        <div>
          <div v-if="invalidFileCount > 0">发现 {{ invalidFileCount }} 个文件名不合规</div>
          <div v-if="unknownStudentCount > 0">发现 {{ unknownStudentCount }} 个学生不在名单中</div>
          <div class="mt-2">请检查日志获取详细信息</div>
        </div>
      </el-alert>
    </el-card>

    <el-card class="results-card" v-if="hasResults">
      <template #header>
        <div class="card-header">
          <h3>学生缺交情况统计</h3>
          <div class="export-actions">
            <el-dropdown @command="handleExport">
              <el-button type="primary">
                导出 <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="excel">导出为Excel</el-dropdown-item>
                  <el-dropdown-item command="csv">导出为CSV</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <el-table
        :data="studentResults"
        style="width: 100%"
        border
      >
        <el-table-column prop="studentId" label="学号" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="missingCount" label="缺交次数" width="100" align="center" />
        <el-table-column prop="totalCount" label="实验总数" width="100" align="center" />
        <el-table-column prop="submissionRate" label="提交率" width="100" align="center">
          <template #default="scope">
            {{ (scope.row.submissionRate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="缺交实验列表" min-width="250">
          <template #default="scope">
            <el-tag
              v-for="experiment in scope.row.missingExperiments"
              :key="experiment.id"
              class="missing-experiment-tag"
            >
              {{ experiment.name }}
            </el-tag>
            <span v-if="scope.row.missingExperiments.length === 0">无</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import FileSystemDirectorySelector from '@/components/FileSystemDirectorySelector.vue'
import ExcelService from '@/utils/ExcelService'
import logger from '@/utils/Logger'

export default {
  name: 'StudentStatistics',
  components: {
    ArrowDown,
    FileSystemDirectorySelector
  },
  setup() {
    const store = useStore()

    // 状态
    const filterForm = ref({
      courseId: '',
      classId: '',
      reportDirectory: ''
    })
    const analyzing = ref(false)
    const studentResults = ref([])
    const showDirectorySelector = ref(false)
    const invalidFileCount = ref(0)
    const unknownStudentCount = ref(0)

    // 计算属性
    const courses = computed(() => {
      return store.getters.getCourses
    })

    const classes = computed(() => {
      return store.getters.getClasses
    })

    const filteredClasses = computed(() => {
      if (!filterForm.value.courseId) {
        return []
      }
      return classes.value.filter(c => c.courseId === filterForm.value.courseId)
    })

    const hasResults = computed(() => {
      return studentResults.value.length > 0
    })

    // 方法
    const loadData = async () => {
      try {
        // 从后端API获取课程和班级数据
        await store.dispatch('fetchCourses')
        await store.dispatch('fetchClasses')

        logger.info('课程和班级数据加载成功')
      } catch (error) {
        logger.error('加载数据失败', error)
        ElMessage.error('加载数据失败')
      }
    }

    const handleCourseChange = () => {
      // 切换课程时重置班级选择
      filterForm.value.classId = ''
    }

    // 打开目录选择器对话框
    const handleSelectDirectory = async () => {
      console.log('StudentStatistics: 打开目录选择器对话框');
      showDirectorySelector.value = true;
      console.log('StudentStatistics: showDirectorySelector =', showDirectorySelector.value);
    }

    // 处理目录选择
    const handleDirectorySelected = (path) => {
      console.log('StudentStatistics: 目录选择回调被触发，path =', path);
      if (path) {
        filterForm.value.reportDirectory = path;
        ElMessage.success('已选择目录: ' + path);
        logger.info('目录选择成功', { path });
      }
      showDirectorySelector.value = false;
      console.log('StudentStatistics: 目录选择完成，showDirectorySelector =', showDirectorySelector.value);
    }

    const analyzeReports = async () => {
      if (!filterForm.value.courseId || !filterForm.value.classId || !filterForm.value.reportDirectory) {
        ElMessage.warning('请选择课程、班级和实验报告目录')
        return
      }

      analyzing.value = true
      try {
        // 显示提示信息
        ElMessage.info('正在分析报告目录，请稍候...')
        console.log('开始分析报告目录:', filterForm.value.reportDirectory)

        // 获取选中的课程和班级
        const selectedCourse = courses.value.find(c => c.id === filterForm.value.courseId)
        const selectedClass = classes.value.find(c => c.id === filterForm.value.classId)

        if (!selectedCourse || !selectedClass) {
          throw new Error('未找到选中的课程或班级')
        }

        // 调用后端API获取学生数据
        await store.dispatch('fetchStudentsByClass', selectedClass.id)

        // 调用后端API获取实验数据
        await store.dispatch('fetchExperimentsByCourse', selectedCourse.id)

        // 调用后端API分析报告
        const analysisResult = await store.dispatch('scanAndAnalyzeReports', {
          classId: selectedClass.id,
          courseId: selectedCourse.id,
          directoryPath: filterForm.value.reportDirectory
        })

        // 处理分析结果
        if (analysisResult && analysisResult.studentStatistics) {
          studentResults.value = analysisResult.studentStatistics.map(stat => ({
            studentId: stat.studentId,
            name: stat.name,
            missingCount: stat.missingCount,
            totalCount: stat.totalCount,
            submissionRate: stat.submissionRate,
            missingExperiments: stat.missingExperiments || []
          }))

          // 显示分析结果摘要
          console.log('分析结果: 共找到', studentResults.value.length, '个学生')
          studentResults.value.forEach(student => {
            console.log(`学生 ${student.name}(${student.studentId}): 总实验数=${student.totalCount}, 缺交数=${student.missingCount}, 提交率=${(student.submissionRate * 100).toFixed(2)}%`)
          })

          // 重置异常计数
          invalidFileCount.value = 0
          unknownStudentCount.value = 0

          // 显示异常信息
          if (analysisResult.invalidFileCount) {
            invalidFileCount.value = analysisResult.invalidFileCount
            ElMessage.warning(`发现 ${invalidFileCount.value} 个文件名不合规，请检查日志获取详细信息`)
            logger.warn(`文件名不合规: ${invalidFileCount.value} 个文件`)
          }

          if (analysisResult.unknownStudentCount) {
            unknownStudentCount.value = analysisResult.unknownStudentCount
            ElMessage.warning(`发现 ${unknownStudentCount.value} 个学生不在名单中，请检查日志获取详细信息`)
            logger.warn(`学生不在名单中: ${unknownStudentCount.value} 个学生`)
          }

          // 兼容旧版异常信息格式
          if (analysisResult.exceptions) {
            const { invalidFormat, unknownStudent } = analysisResult.exceptions

            if (invalidFormat && invalidFormat.length > 0 && invalidFileCount.value === 0) {
              invalidFileCount.value = invalidFormat.length
              ElMessage.warning(`发现 ${invalidFormat.length} 个文件名不合规，请检查日志获取详细信息`)
              logger.warn(`文件名不合规: ${invalidFormat.length} 个文件`)
            }

            if (unknownStudent && unknownStudent.length > 0 && unknownStudentCount.value === 0) {
              unknownStudentCount.value = unknownStudent.length
              ElMessage.warning(`发现 ${unknownStudent.length} 个学生不在名单中，请检查日志获取详细信息`)
              logger.warn(`学生不在名单中: ${unknownStudent.length} 个学生`)
            }
          }

          // 显示成功处理的文件数量
          if (analysisResult.processedCount) {
            ElMessage.success(`成功处理 ${analysisResult.processedCount} 个实验报告文件`)
            logger.info(`成功处理 ${analysisResult.processedCount} 个实验报告文件`)
          }
        } else {
          studentResults.value = []
          throw new Error('分析结果为空')
        }

        logger.info('学生维度统计完成', {
          courseId: selectedCourse.id,
          classId: selectedClass.id,
          directory: filterForm.value.reportDirectory,
          studentCount: studentResults.value.length
        })
        ElMessage.success('学生维度统计完成')
      } catch (error) {
        logger.error('学生维度统计失败', error)
        ElMessage.error(`学生维度统计失败: ${error.message}`)

        // 检查是否是目录不存在或无法访问的错误
        if (error.message.includes('目录不存在') || error.message.includes('无法访问')) {
          ElMessage.error(`目录 "${filterForm.value.reportDirectory}" 不存在或无法访问，请检查路径是否正确`)
        }
      } finally {
        analyzing.value = false
      }
    }

    const handleExport = (command) => {
      if (command === 'excel') {
        exportToExcel()
      } else if (command === 'csv') {
        exportToCSV()
      }
    }

    const exportToExcel = () => {
      try {
        // 获取当前选中的课程和班级
        const selectedCourse = courses.value.find(c => c.id === filterForm.value.courseId)
        const selectedClass = filteredClasses.value.find(c => c.id === filterForm.value.classId)

        if (!selectedCourse || !selectedClass) {
          ElMessage.warning('请先选择课程和班级')
          return
        }

        // 准备导出数据
        const exportData = studentResults.value.map(result => ({
          '学号': result.studentId,
          '姓名': result.name,
          '缺交次数': result.missingCount,
          '实验总数': result.totalCount,
          '提交率': `${(result.submissionRate * 100).toFixed(2)}%`,
          '缺交实验': result.missingExperiments.map(e => e.name).join(', ')
        }))

        // 构建文件名：课程名_班级名_学生缺交情况统计
        const fileName = `${selectedCourse.name}_${selectedClass.name}_学生缺交情况统计`

        // 导出Excel
        ExcelService.exportToExcel(exportData, fileName)
        logger.info('导出Excel成功', { fileName })
      } catch (error) {
        logger.error('导出Excel失败', error)
        ElMessage.error('导出Excel失败')
      }
    }

    const exportToCSV = () => {
      try {
        // 获取当前选中的课程和班级
        const selectedCourse = courses.value.find(c => c.id === filterForm.value.courseId)
        const selectedClass = filteredClasses.value.find(c => c.id === filterForm.value.classId)

        if (!selectedCourse || !selectedClass) {
          ElMessage.warning('请先选择课程和班级')
          return
        }

        // 准备导出数据
        const exportData = studentResults.value.map(result => ({
          '学号': result.studentId,
          '姓名': result.name,
          '缺交次数': result.missingCount,
          '实验总数': result.totalCount,
          '提交率': `${(result.submissionRate * 100).toFixed(2)}%`,
          '缺交实验': result.missingExperiments.map(e => e.name).join(', ')
        }))

        // 构建文件名：课程名_班级名_学生缺交情况统计
        const fileName = `${selectedCourse.name}_${selectedClass.name}_学生缺交情况统计`

        // 导出CSV
        ExcelService.exportToCSV(exportData, fileName)
        logger.info('导出CSV成功', { fileName })
      } catch (error) {
        logger.error('导出CSV失败', error)
        ElMessage.error('导出CSV失败')
      }
    }

    // 生命周期钩子
    onMounted(() => {
      loadData()
    })

    return {
      filterForm,
      analyzing,
      studentResults,
      courses,
      filteredClasses,
      hasResults,
      showDirectorySelector,
      invalidFileCount,
      unknownStudentCount,
      handleCourseChange,
      handleSelectDirectory,
      handleDirectorySelected,
      analyzeReports,
      handleExport,
      exportResults: handleExport
    }
  }
}
</script>

<style scoped>
.student-statistics-container {
  max-width: 1200px;
  margin: 0 auto;
}

.filter-card {
  margin-bottom: 20px;
}

.results-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2, .card-header h3 {
  margin: 0;
  color: #303133;
}

.filter-form {
  margin-top: 20px;
}

.missing-experiment-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.export-actions {
  display: flex;
  align-items: center;
}
</style>
